<!-- eslint-disable vue/multi-word-component-names -->
<script setup lang="ts">
import EditTable from '@/views/customizedPage/BaoBiaoGuanLi/components/editTable.vue'
import { Delete, Finished, Plus, Search } from '@element-plus/icons-vue'
import { nextTick, ref } from 'vue'
import instance from '@/utils/serve'
import { ElMessage } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits<{
  (e: 'update:isShow', value: boolean): void
}>()

const scrollbarRef = ref<any>(null)
const visible = ref(false)
const isTree = ref(false)
const saving = ref(false)
const treeRef = ref<any>(null)
const tree = ref<any>({ loading: false, data: [] })
const tableRef = ref<any>(null)
const columns = ref<any>([
  {
    prop: 'item_id',
    label: '字典项编码',
    'min-width': 100,
    editor: {
      validator: (r: any, d: any) =>
        !!r.item_id && !d.find((i: any) => i != r && i.item_id == r.item_id)
    }
  }, //非空且不重复
  {
    prop: 'item_value',
    label: '字典项名称',
    'min-width': 150,
    editor: { validator: (r: any) => !!r.item_value }
  }, //非空
  { prop: 'order_no', label: '排序', width: 80, editor: { type: 'number' } }
])
const table = ref<any>({ loading: false, list: { total: 0, rows: [] }, columns: columns.value })
const form = ref<any>({
  pagination: true,
  page: 1,
  rows: 20,
  dbName: 'report',
  sqlParam: { search_text: '' }
})

const addOptions = () => {
  tableRef.value.addRow({ parent_id: form.value.sqlParam.parent_id || null })
}

const removeSelected = () => {
  tableRef.value.removeSelected()
}

const handleSizeChange = (val: number) => {
  form.value.page = 1
  form.value.rows = val
}

const handleCurrentChange = (val: number) => {
  form.value.page = val
}

const Cancel = () => {
  form.value.search_text = ''
  emit('update:isShow', false)
}

const show = (row: any) => {
  // console.log('xxx', row)

  tree.value.data = []
  table.value.list = { totla: 0, rows: [] }
  form.value.sqlParam = { search_text: null, dict_id: row.dict_id, parent_id: null }
  if ((isTree.value = row.is_tree == 1)) getTree()
  else getDictProps()
  visible.value = true
}
const getTree = async () => {
  tree.value.loading = true
  await instance
    .post('/common/getTree', {
      sqlId: 'dict.getPropsList',
      sqlParam: { dict_id: form.value.sqlParam.dict_id },
      field: { id: 'item_id', name: 'item_value' },
      dbName: 'report'
    })
    .then((res: any) => {
      tree.value.loading = false
      tree.value.data = [{ id: '', text: '根目录', children: res }]
      nodeClick(tree.value.data[0])
      nextTick(() => {
        treeRef.value.setCurrentKey(form.value.sqlParam.parent_id)
        scrollbarRef.value.update()
      })
    })
}

const getDictProps = async (page?: any) => {
  if (isNaN(page)) form.value.page = 1
  table.value.loading = true
  await instance
    .post('/common/getDataGrid', { sqlId: 'dict.getDictProps', ...form.value })
    .then((res) => {
      table.value.loading = false
      table.value.list = res
      tableRef.value.loadData(table.value.list.rows)
    })
}
const save = async () => {
  let param = tableRef.value.getChanges()
  if (param === false) return //编辑校验不通过
  if (!param.insert.length && !param.updated.length && !param.deleted.length)
    return ElMessage({ message: '无数据变更', type: 'error' })
  let numberVal = (v: any) => (v != null && v != '' ? Number(v) : null)
  param.insert = param.insert.map((i: any) => ({
    item_id: i.item_id,
    item_value: i.item_value,
    parent_id: i.parent_id,
    order_no: numberVal(i.order_no)
  }))
  param.updated = param.updated.map((i: any) => ({
    item_id: i.item_id,
    item_value: i.item_value,
    parent_id: i.parent_id,
    order_no: numberVal(i.order_no),
    ori: JSON.parse(i.ori)
  }))
  param.deleted = param.deleted.map((i: any) => ({ item_id: i.item_id }))
  param.dict_id = form.value.sqlParam.dict_id
  param.isTree = isTree.value
  saving.value = true
  await instance.post('/dict/saveProps', param).then((res: any) => {
    saving.value = false
    if (res.code == 0) {
      ElMessage({ message: res.message, type: 'success' }) // this.$message.success(res.data.message)
      isTree.value ? getTree() : getDictProps()
    } else {
      ElMessage({ message: res.message, type: 'error' })
    }
  })
}
const nodeClick = (node: any) => {
  form.value.sqlParam.parent_id = node.id
  getDictProps()
}

const regionTreeFn = (node: Node, resolve: (data: any[]) => void) => {
  // console.log(node)

  // 树形结构地域
  if (node.level === 0) {
    const info = tree.value.data.map((item: any) => {
      return {
        value: item.id,
        label: item.text,
        children: item.children
      }
    })
    return resolve(info)
  }

  if (node.level > 1) {
    if (!node.data.children) {
      node.data.children = []
    } else {
      setTimeout(() => {
        const data = node.data.children
        resolve(data)
      }, 200)
    }
  }
  setTimeout(() => {
    const data = node.data.children
    resolve(data)
  }, 200)
}

defineExpose({
  show
})
</script>
<template>
  <!-- <div></div> -->
  <el-dialog title="字典项配置" width="70%" @close="Cancel()" :model-value="isShow">
    <div class="dicOptionsBox">
      <div v-if="isTree" class="left" v-loading="tree.loading">
        <el-scrollbar ref="scrollbarRef" class="h-100">
          <!--  lazy
            :load="regionTreeFn" :cache-data="tree.data"-->
          <el-tree
            lazy
            :load="regionTreeFn"
            ref="treeRef"
            :data="tree.data"
            node-key="id"
            :props="{ label: 'text' }"
            :expand-on-click-node="false"
            highlight-current
            @node-click="nodeClick"
          />
        </el-scrollbar>
      </div>
      <div class="flexBox" v-loading="table.loading">
        <div style="margin-bottom: 15px">
          <el-form :inline="true" :model="form" style="margin-top: 15px">
            <el-form-item label="字典项编码/名称：">
              <el-input
                v-model="form.sqlParam.search_text"
                placeholder="请输入字典项编码/名称"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button :icon="Search" type="primary" @click="getDictProps">查询</el-button>
              <el-button :icon="Plus" type="success" @click="addOptions" plain>新增</el-button>
              <el-button :icon="Delete" type="danger" @click="removeSelected" plain>
                批量删除
              </el-button>
              <el-button :icon="Finished" type="primary" :loading="saving" @click="save">
                保存
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <EditTable class="TableBox" ref="tableRef" :columns="table.columns">
          <template v-slot:append>
            <el-table-column prop="operate_date" label="维护时间" width="160" align="center" />
          </template>
        </EditTable>
        <el-pagination
          class="paginationBox"
          v-model:current-page="form.page"
          v-model:page-size="form.rows"
          :page-sizes="[10, 20, 30, 40]"
          size="default"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="Number(table.list.total)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </el-dialog>
</template>

<style lang="less" scoped>
.dicOptionsBox {
  display: flex;
  height: calc(80vh - 95px);
  margin: -10px 0;
  .flexBox {
    flex: 1;
    :deep(.TableBox) {
      // width: 1200px !important;
      height: calc(80vh - 230px);
    }
  }

  .left {
    height: 100%;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    margin-right: 15px;

    .el-scrollbar {
      width: 250px;
      height: 100%;

      .el-scrollbar__wrap {
        overflow-x: hidden;
      }
    }

    .el-tree > .el-tree-node {
      min-width: 100%;
      display: inline-block;
    }

    .el-tree-node.is-current > .el-tree-node__content {
      background-color: #9bdeff !important;
    }
  }
}
</style>
